﻿using System;
using System.Collections.ObjectModel;
using System.Data;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;

using PublicDomain.Data.Csv.Properties;

namespace PublicDomain.Data.Csv.Metadata
{
    [DataContract(Namespace = "www.publicdomain.net\\data\\csv\\metadata\\2013-11-26\\", Name = "CsvDataFormat")]
    public class CsvDataFormat
    {
        private Collection<CsvColumnDefinition> csvColumnsDefinitions;

        [DataMember(Name = "Name", IsRequired = true)]
        public string Name { get; set; }

        [DataMember(Name = "CsvColumnsDefinitions", IsRequired = true)]
        public Collection<CsvColumnDefinition> CsvColumnsDefinitions
        {
            get
            {
                if (this.csvColumnsDefinitions == null)
                {
                    this.csvColumnsDefinitions = new Collection<CsvColumnDefinition>();
                }

                return this.csvColumnsDefinitions;
            }

            set
            {
                this.csvColumnsDefinitions = value;
            }
        }

        public static CsvDataFormat CreateDefaultCsvDataFormat(string fileName, string[] headerColumnsText) // TODO fileName or filePath???
        {
            if (headerColumnsText == null)
            {
                throw new ArgumentNullException("headerColumnsText");
            }

            var result = new CsvDataFormat { Name = Path.GetFileNameWithoutExtension(fileName) };

            for (int i = 0; i < headerColumnsText.Length; i++)
            {
                var csvColumnSchema = new CsvColumnDefinition
                {
                    ColumnName = String.Format(CultureInfo.CurrentCulture, "Column{0}", i),
                    ColumnOrdinal = i,
                    ColumnSize = int.MaxValue,
                    DataType = DbType.String
                };

                result.CsvColumnsDefinitions.Add(csvColumnSchema);
            }

            return result;
        }

        public CsvColumnDefinition GetCsvColumnSchema(int columnOrdinal)
        {
            var result = this.CsvColumnsDefinitions.Single(ColumnSchema => ColumnSchema.ColumnOrdinal == columnOrdinal);

            return result;
        }

        public CsvColumnDefinition GetCsvColumnSchema(string columnName)
        {
            if (columnName == null)
            {
                throw new ArgumentNullException("columnName");
            }

            if (String.IsNullOrEmpty(columnName))
            {
                throw new ArgumentException(Resources.ParameterColumnNameError, "columnName");
            }

            var result = this.CsvColumnsDefinitions.Single(ColumnSchema => columnName.Equals(ColumnSchema.ColumnName, StringComparison.OrdinalIgnoreCase));

            return result;
        }
    }
}
